package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"practice-one/models/cache"
	"practice-one/models/mysql"
	"practice-one/pkg"

	"practice-one/userrpc/internal/svc"
	"practice-one/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *userrpc.UpdatePasswordRequest) (*userrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.FindUserByTel(mysql.DB, in.Tel)
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("该手机号未注册")
	}
	result, _ := cache.Rdb.Get(l.ctx, "smsCode_"+in.Tel).Result()
	if result != in.SmsCode {
		return nil, errors.New("手机验证码错误,请重试")
	}
	if pkg.Md5(in.OldPassword) != user.Password {
		return nil, errors.New("原密码错误,请重试")
	}
	if pkg.Md5(in.NewPassword) != pkg.Md5(in.AckPassword) {
		return nil, errors.New("两次密码不一致,请重新输入")
	}
	if pkg.Md5(in.NewPassword) == pkg.Md5(in.OldPassword) {
		return nil, errors.New("修改后的密码与原密码一致,修改失败")
	}
	users := &mysql.User{
		Model:    gorm.Model{ID: user.ID},
		Password: pkg.Md5(in.NewPassword),
	}
	if err = users.UpdateUser(mysql.DB); err != nil {
		return nil, errors.New("修改失败")
	}
	return &userrpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
